using System;
using System.Diagnostics;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Xml;
using Facebook.Core.Exceptions;

namespace Facebook.Core
{
    public class FacebookMessageInspector : IClientMessageInspector
    {
        #region Implementation of IClientMessageInspector

        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            return request;
        }

        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            MessageBuffer messageBuffer = reply.CreateBufferedCopy(int.MaxValue);
            Message message = messageBuffer.CreateMessage();

            XmlDictionaryReader contents = message.GetReaderAtBodyContents();
            XmlDocument document = new XmlDocument();

            try
            {
                document.Load(contents);
            }
            catch (Exception e)
            {
                if(document.GetElementsByTagName("error_response").Count > 0)
                {
                    int errorCode = Convert.ToInt32(document.GetElementsByTagName("error_code")[0].InnerXml);
                    throw new FacebookException((FacebookErrorCodes) errorCode);
                }
            }

            Debug.WriteLine(String.Empty);
            Debug.WriteLine("<== Received Message ==>");
            StringWriter writer = new StringWriter();
            XmlTextWriter textWriter = new XmlTextWriter(writer);
            textWriter.Formatting = Formatting.Indented;
            document.WriteTo(textWriter);
            Debug.Write(writer);
            Debug.WriteLine(String.Empty);
            Debug.WriteLine("<== End Message==>");
            Debug.WriteLine(String.Empty);

            reply = messageBuffer.CreateMessage();
            messageBuffer.Close();
        }

        #endregion
    }
}